<?php
    session_start();

    $page = isset($_POST['page']) ? $_POST['page'] : 1;
    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'name';
    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
    $query = isset($_POST['query']) ? $_POST['query'] : false;
    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : false;

	//unset($_SESSION['ORDER_DETAIL']);
	//print_r($_SESSION['ORDER_DETAIL']);

    if(isset($_GET['Add'])){ // this is for adding records		
        $rows = $_SESSION['ORDER_DETAIL'];
        $exists_id = BillCodeExists($_GET['BILLCODE'], $rows);
        if ($exists_id > 0)
        {
	        $rows[$exists_id] = array(
	            'BILLCODE'	=>$_GET['BILLCODE'], 
	            'QTY'		=>$_GET['QTY'], 
	            'BILLDESC'	=>$_GET['BILLDESC'], 
	            'PRICE'		=>$_GET['PRICE'],
	            'AMOUNT'	=>$_GET['AMOUNT'],
	            'ORDCAMPD'	=>$_GET['ORDCAMPD']
	        );			
		}
		else
		{		
	        $last_id = array_pop(array_keys($_SESSION['ORDER_DETAIL']));
	        $rows[$last_id+1] = array(
	            'BILLCODE'	=>$_GET['BILLCODE'], 
	            'QTY'		=>$_GET['QTY'], 
	            'BILLDESC'	=>$_GET['BILLDESC'], 
	            'PRICE'		=>$_GET['PRICE'],
	            'AMOUNT'	=>$_GET['AMOUNT'],
	            'ORDCAMPD'	=>$_GET['ORDCAMPD']
	        );
        }
        $_SESSION['ORDER_DETAIL'] = $rows;       	
    }
    elseif(isset($_GET['Delete'])){ // this is for removing records
        $rows = $_SESSION['ORDER_DETAIL'];
        unset($rows[trim($_GET['Delete'])]);  // to remove the \n
        $_SESSION['ORDER_DETAIL'] = $rows;
    }
    else{
        if(isset($_SESSION['ORDER_DETAIL'])){ // get session if there is one
            $rows = $_SESSION['ORDER_DETAIL'];
            krsort($rows);
        }

        header("Content-type: application/json");
        $jsonData = array('page'=>$page,'total'=>0,'rows'=>array());
        
        foreach($rows AS $rowNum => $row){
            //If cell's elements have named keys, they must match column names
            //Only cell's with named keys and matching columns are order independent.
            $entry = array('id' => $rowNum,
                'cell'=>array(
                    'LISTNO'       => $rowNum,
                    'BILLCODE'     => $row['BILLCODE'],
                    'QTY' 		   => $row['QTY'],
                    'BILLDESC'     => $row['BILLDESC'],
                    'PRICE'        => $row['PRICE'],
                    'AMOUNT'       => $row['AMOUNT']
                )
            );
            $jsonData['rows'][] = $entry;
        }
        $jsonData['total'] = count($rows);
        echo json_encode($jsonData);
	}
	
	//print_r($rows);
	function BillCodeExists($billcode, $array)
	{
		if (is_array($array))
		{
			foreach ($array AS $rowNum => $row)
			{
				if ($billcode == $row['BILLCODE']) return $rowNum;
			}			
		}
		return 0;
	}